package controller.environment;

import java.util.ArrayList;

import reference.constants.ConstantProblem;
import view.completeView.GroundManagerListener;
import controller.environment.ground.Ground;
import controller.environment.ground.GroundFertile;
import controller.taskManagement.TaskManagement;

public class GroundManager {
	
	private static GroundManager m_groundManager;
	private Ground[][] m_grounds;
	private ArrayList<GroundManagerListener> listeners;
	
	private GroundManager(){
		listeners = new ArrayList<GroundManagerListener>();
		m_grounds = new Ground[ConstantProblem.GROUND_WIDTH][ConstantProblem.GROUND_HEIGHT];
		for(int i=0;i<ConstantProblem.GROUND_WIDTH;i++){
			for(int j=0;j<ConstantProblem.GROUND_HEIGHT;j++){
				m_grounds[i][j] = new GroundFertile(this, i, j);
			}
		}
	}
	
	public static GroundManager getInstance(){
		if(m_groundManager==null)
			m_groundManager = new GroundManager();
		return m_groundManager;
	}
	
	public Ground getGround(int pos_x, int pos_y){
		if(pos_x<0 || pos_y<0 || pos_x>=m_grounds.length || pos_y>=m_grounds[0].length)
			return null;
		return m_grounds[pos_x][pos_y];
	}
	
	public boolean setNewGround(Ground new_ground, int pos_x, int pos_y){
		m_grounds[pos_x][pos_y] = new_ground;
		for(GroundManagerListener listener : listeners){
			listener.changeGround(new_ground, pos_x, pos_y);
		}
		TaskManagement.getTaskManagement().addTask(new_ground);
		return true;
	}
	
	public void addListener(GroundManagerListener listener){
		listeners.add(listener);
	}
	
	public void removeListener(GroundManagerListener listener){
		listeners.remove(listener);
	}
}
